package com.mera.tektronix.csviewer.services

import org.apache.commons.logging.LogFactory
import org.springframework.context.MessageSource

import com.mera.tektronix.csviewer.common.api.*
import com.mera.tektronix.csviewer.common.dto.*
import com.mera.tektronix.csviewer.common.exception.LogicException
import com.mera.tektronix.csviewer.domain.*
import com.mera.tektronix.csviewer.transformers.ITransformer

class EmployeeRemoteService implements IEmployeeService {
	static transactional = true
	private static final log = LogFactory.getLog(EmployeeRemoteService.class)

	ITransformer employeeTransformer
	MessageSource messageSource
	
	@Override
	public List<EmployeeDto> getList() {
		List<Employee> employees = Employee.list(sort: "id", order: "asc");
		return employeeTransformer.transformDomainToDtoList(employees);
	}
	
	@Override
	public List<EmployeeDto> getListByProjectId(Long projectId) {
		Project projTo = Project.get(projectId);
		List<Employee> employees = Employee.findAllByProjectLike(projTo).sort( { a, b -> a.id <=> b.id } as Comparator );
		return employeeTransformer.transformDomainToDtoList(employees);
	}
	
	@Override
	public EmployeeDto getEmployeeById(Long id) {
		Employee emp = Employee.get(id);
		return employeeTransformer.transformDomainToDto(emp);
	}
	
	@Override
	public void addEmployee(EmployeeDto employee) throws LogicException {
		Employee emp = employeeTransformer.transformDtoToDomain(employee);

		if(!emp.save()) {
			def err = emp.errors.allErrors.collect {[
						  errorMessage : messageSource.getMessage(it, null)
					  ]}
			
			throw new LogicException(err);
		}
	}
	
	@Override
	public void deleteEmployee(Long id) {
		Employee emp = Employee.get(id);
		emp.delete(flush : true);
	}
}
